package com.example.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.cdc.server.CDCServer;
import com.example.mapper.SysCdcListenerMapper;
import com.example.po.SysCdcListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class SysCdcListenerServiceImpl extends ServiceImpl<SysCdcListenerMapper, SysCdcListener> implements SysCdcListenerService {

    Logger logger = LoggerFactory.getLogger(getClass());

    private Map<Long, CDCServer> serverMap = new ConcurrentHashMap<>();

    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public List<SysCdcListener> findList() {
        return list();
    }

    @Override
    public void startAll() {
        for (SysCdcListener sysCdcListener : findList()) {
            CDCServer cdcServer = new CDCServer(sysCdcListener, redisTemplate);
            cdcServer.init();
            cdcServer.start();
            this.serverMap.put(sysCdcListener.getId(), cdcServer);
        }
    }

    @Override
    public void stopAll() throws Exception {
        for (CDCServer cdcServer : this.serverMap.values()) {
            cdcServer.stop();
        }
    }
}
